package carson.web.mvc.core.results;

import carson.web.mvc.core.exceptions.ResponseFileException;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * 将文件流发送到响应
 *
 * @author Carson Chen
 */
public class FileStreamResult extends AbstractFileResult {

    /**
     * 实例化FileStreamResult
     *
     * @param fileStream       文件流
     * @param contentType      内容类型
     * @param fileDownloadName 下载时的文件名
     */
    public FileStreamResult(InputStream fileStream, String contentType, String fileDownloadName) {
        super(contentType);
        this.fileStream = fileStream;
        setFileDownloadName(fileDownloadName);
    }

    private InputStream fileStream;

    /**
     * 获取文件流
     *
     * @return 文件流
     */
    public InputStream getFileStream() {
        return fileStream;
    }

    @Override
    protected void writeFile(HttpServletResponse response) throws Exception {
        //try(Closeable){}写法能够自动关闭对象，不需要显式调用close方法
        try (InputStream in = this.fileStream) {
            response.setHeader("content-disposition", "attachment; filename="
                    + java.net.URLEncoder.encode(getFileDownloadName(), "UTF-8"));
            try (ServletOutputStream out = response.getOutputStream()) {
                StreamUtils.copy(in, out);
            }
        } catch (Exception e) {
            throw new ResponseFileException("导出文件异常", e);
        }
    }
}
